import {Handler} from "./Handler";
import {Interactable, InteractEvent} from "interactjs";
import * as interact from "interactjs";
import {MapRenderer} from "../render/MapRenderer";
import {MapCamera} from "../render/MapCamera";

export class GesturableHandler extends Handler {
    protected interactable: Interactable;

    protected camera: MapCamera;

    protected mapRenderer: MapRenderer;

    init(): void {
        this.mapRenderer = this.map.mapRenderer;
        this.camera = this.mapRenderer.camera;
    }

    enable(): void {
        this.interactable = interact(this.map.container).gesturable({
            onmove: e => this.onMove(e),
            onstart: e => this.onStart(e),
            onend: e => this.onEnd(e)
        });
    }

    disable(): void {
        if (this.interactable) {
            (this.interactable as any).options.drag.enabled = false;
        }
    }

    onMove(e: InteractEvent): any {
        this.camera.zoomBy(e.ds);

        this.mapRenderer.render();
    }

    private onStart(e: interact.InteractEvent) {
        this.map.eventDispatcher.dispatchEvent({
            type: "gesturestart"
        });
    }

    private onEnd(e: interact.InteractEvent) {
        this.map.eventDispatcher.dispatchEvent({
            type: "gestureend"
        });
    }
}
